package top.codingfly.examples;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.logging.LogLevel;
import top.codingfly.netty.server.NettyServer;

import java.util.Timer;
import java.util.TimerTask;

public class ServerExample {

    public static void main(String[] args) {
        while (true) {
            CommonHandler serverHandler = new CommonHandler() {
                // 解码之后, 会自动调handle方法
                @Override
                public <T> void handle(ChannelHandlerContext ctx, T msg) throws Exception {
                    ProtocolPacket packet = (ProtocolPacket) msg;
                    if (new Integer(2).equals(packet.type)) {
                        System.out.println(new String(packet.dataBytes));
                        // 把这个包转发回去给客户端
                        ctx.channel().writeAndFlush(packet);
                    } else {
                        System.out.println("====================");
                    }
                }
            };
            NettyServer nettyServer = new NettyServer(serverHandler, 2, 5, LogLevel.DEBUG);
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    nettyServer.close();
                }
            };
            timer.schedule(task, 3333); // 5秒后执行任务
            nettyServer.start(1333);
        }
    }

}
